package com.ray.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.IntStream;

import org.apache.ibatis.javassist.SerialVersionUID;
import org.apache.xmlbeans.impl.xb.xsdschema.NarrowMaxMin;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.appengine.api.search.query.ExpressionParser.condExpr_return;
import com.ray.bean.AttendPlanBean;
import com.ray.bean.CompanyBean;
import com.ray.bean.CompanyMaterialTableBean;
import com.ray.bean.DormManageToUserBean;
import com.ray.bean.DormUserUseRecord;
import com.ray.bean.DutyBean;
import com.ray.bean.EcsMonitorBean;
import com.ray.bean.OrderBean;
import com.ray.bean.OrderFinishMaterialBean;
import com.ray.bean.ProductionExceptionBean;
import com.ray.bean.UserBean;
import com.ray.bean.WarehouseInOutDetailBean;
import com.ray.bean.WarehouseInSumMoneyBean;
import com.ray.bean.WeiXinPeopleBean;
import com.ray.bean.MachinepRrocessCapacityBean.DayCapacity;
import com.ray.mapper.BasicDataMapper;
import com.ray.mapper.CompanyMapper;
import com.ray.mapper.DerviceMapper;
import com.ray.mapper.DingTalkMapper;
import com.ray.mapper.DormUserUseRecordMapper;
import com.ray.mapper.EnergyMapper;
import com.ray.mapper.EquipmentMapper;
import com.ray.mapper.OrderMapper;
import com.ray.mapper.PurchaseOrderMapper;
import com.ray.mapper.UserMapper;
import com.ray.mapper.WeiXinPeopleMapper;
import com.ray.mapper.WorkshopMapper;
import com.ray.pojo.EquipmentDetail;
import com.ray.pojo.EquipmentRecordPojo;
import com.ray.pojo.PurchaseOrderDetailPojo;
import com.ray.pojo.attend.PendingApprovalInfoPojo;
import com.ray.protocol.constants.Color;
import com.ray.protocol.constants.TemplateClickUrl;
import com.ray.protocol.constants.TemplateID;
import com.ray.protocol.constants.TimeConst;
import com.ray.protocol.constants.WeChatMessageType;
import com.ray.util.ArrayUtils;
import com.ray.util.RedirectUrlUtil;
import com.ray.util.TimeAndUnix;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.baidu.BaiduSimilarPicSearchUtils;
import com.ray.util.baidu.Brief;
import com.ray.util.baidu.Tags;
import com.ray.util.redis.RedisCache;
import com.ray.util.redis.RedisKey;
import com.ray.util.weixin.WeixinTemplateList;
import com.ray.util.weixin.WeixinTemplateSender;
import com.thoughtworks.xstream.converters.reflection.ExternalizableConverter;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

//定时任务
@Service
public class ScheduleService {

    @Autowired
    DerviceMapper derviceMapper;
    @Autowired
    WorkshopMapper workShopMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    EquipmentMapper equipmentMapper;
    @Autowired
    EquipmentService equipmentService;
    @Autowired
    EnergyMapper energyMapper;
    @Autowired
    WeiXinPeopleMapper weiXinPeopleMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    DingTalkService dingTalkService;
    @Autowired
    DingTalkMapper dingTalkMapper;
    @Autowired
    AttendanceService attendanceService;
    @Autowired
    WorkshopMapper workshopMapper;
    @Autowired
    PurchaseOrderMapper purchaseOrderMapper;
    @Autowired
    DormUserUseRecordMapper dormUserUseRecordMapper;

    @Autowired
    UserService userService;
    @Autowired
    WeiXinService weiXinService;
    @Autowired
    WeChatToMessageService weChatToMessageService;
    @Autowired
    BasicDataMapper basicDataMapper;
    @Autowired
    CompanyMaterialService companyMaterialService;
    @Autowired
    BasicDataService basicDataService;
    @Autowired
    MaterService materService ;
    @Autowired
    OrderService orderService;
    @Autowired
    CompanyMapper companyMapper;


    // //定时查找电气时间(已quxiao)
    // public void querryPowerTimeMethod() {
    // System.out.println("查询电气时间段定时器执行。。。。。");
    // //参数map
    // Map paramMap=new HashMap();
    // Date date=new Date();
    // SimpleDateFormat formatter = new SimpleDateFormat("2017-01-01 HH:mm:ss");
    // //获取当前时间(日期固定为2017-01-01 比较)
    // String nowTime = formatter.format(date);
    // System.out.println(nowTime);
    // //获取当前星期几
    // formatter = new SimpleDateFormat("EEEE");
    // String nowWeek= formatter.format(date);
    // //获取当前日期
    // formatter = new SimpleDateFormat("yyyy-MM-dd");
    // String nowDay=formatter.format(date);
    //
    // paramMap.put("nowTime", nowTime);
    // paramMap.put("nowWeek", nowWeek);
    // paramMap.put("nowDay", nowDay);
    //
    // //获取开始时间为当前时间的数据
    // List<PowerTimeBean>
    // startList=derviceMapper.getStartPowerTimeBeanByMap(paramMap);
    // if(startList.size()>0) {
    // //批量设置电气action为类型
    // derviceMapper.setListPowerAction(startList);
    // }
    // List<PowerTimeBean> endList=derviceMapper.getEndPowerTimeBeanByMap(paramMap);
    // if(endList.size()>0) {
    // //批量设置电气action为0
    // derviceMapper.setListPowerActionToZero(endList);
    // }
    // }

    /**
     * 修改已完成订单的sort为-1
     */
    public void updateFinishOrderSortMethod() {
        // //更新仪表记录
        // Map map=new HashMap();
        // energyMapper.insertEquipmentRecord(map);
        System.out.println("设置订单生产顺序定时器执行");
        // 查找生产订单主表里的公司名称
        List<String> companyList = orderMapper.getOrderCompany();
        for (String str : companyList) {
            this.updateOneComapnyFinishOrderSort(str);
        }
    }

    // 修改单个公司的订单顺序
    public void updateOneComapnyFinishOrderSort(String str) {
        List<String> orderIdList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("loginCompany", str);
        map.put("company", str);
        // 获取公司下订单生产情况
        List<OrderFinishMaterialBean> listProdution = workShopMapper.getReportFinishOrderDetail(map);
        // 获取公司下订单物料条数
        List<OrderFinishMaterialBean> listOrderMaterial = orderMapper.getOrderMaterialCount(map);
        // 遍历生产单
        for (OrderFinishMaterialBean prodution : listProdution) {
            // 遍历订单物料
            for (OrderFinishMaterialBean orderMaterial : listOrderMaterial) {
                // 如果订单编号相等
                if (orderMaterial.getOrderId().equals(prodution.getOrderId())) {
                    // 如果生产完成的物料条数大于等于订单物料条数
                    if (prodution.getCount() >= orderMaterial.getCount()) {
                        // 添加到list中sort更改为-1
                        orderIdList.add(prodution.getOrderId());
                        break;
                        // 跳出本循环
                    } else {
                        continue;
                    }
                } else {// 不相等跳过本次循环
                    continue;
                }
            }
        }
        // 有生产完成的单子则修改
        if (orderIdList != null && orderIdList.size() > 0) {
            map.put("orderIdList", orderIdList);
            orderMapper.updateFinishOrderSort(map);
        }
        map.remove("orderIdList");
        this.sortOder(map);
    }

    // 设置订单生产顺序
    private void sortOder(Map<String, Object> map) {
        List<OrderBean> listOrder = orderMapper.getAleradySort(map);
        if (listOrder != null && listOrder.size() > 0) {
            int sort = 1;
            for (OrderBean order : listOrder) {
                order.setSort(sort);
                sort++;
            }
            //如果订单数量超过五百（）
            if(listOrder.size()>500) {
            	int index=0;
            	double lengthd=Math.ceil(listOrder.size()/500.0);
            	int length=(int)lengthd;
            	for(int i=1;i<length;i++) {
            		List<OrderBean> orderBeans=listOrder.subList(index, i*500-1);
            		map.put("listOrder", orderBeans);
                    // 重新设置生产订单顺序
                    orderMapper.setOrderSort(map);
            		index=i*500;
            	}
            	if(listOrder.size()%500 != 0) {
                	List<OrderBean> orderBeans=listOrder.subList(index, listOrder.size());
            		map.put("listOrder", orderBeans);
                    // 重新设置生产订单顺序
                    orderMapper.setOrderSort(map);
                }
            }
            
        }
        map.remove("listOrder");
        // 获取未设置的订单编号信息
        listOrder = orderMapper.getNotSetSort(map);
        for (OrderBean order : listOrder) {
            int sort = 1;
            // 获取最靠近的交货日期的订单顺序
            OrderBean orderBean = orderMapper.getMaxSortOrder(order);
            if (orderBean == null || orderBean.getSort() == null) {
                orderBean = new OrderBean();
                orderBean.setSort(0);
            }
            sort = orderBean.getSort() + 1;
            order.setSort(sort);
            // 修改订单排序
            orderMapper.setOrderSortByJiaoDate(order);
        }
    }

    // 设置设备状态
    public void setEquipmentStateMethod() {
        Set<String> orderSet = new HashSet();
        Map map = new HashMap();
        map.put("Schedule", 1);
        List<EcsMonitorBean> listEcs = equipmentMapper.getEcsMonitorData(map);
        for (EcsMonitorBean ecsMonitorBean : listEcs) {
            // 如果设备加工数量大于投料数加调机数，停止设备
            if (ecsMonitorBean.getSumYield() >= ecsMonitorBean.getFeedTotal()
                    + ecsMonitorBean.getAdjustingMachineCount()) {
                orderSet.add(ecsMonitorBean.getOrderId());
            }
        }
        if (orderSet.size() > 0) {
            equipmentMapper.updateEquipmentState(orderSet, 1);// 设置设备不再继续工作
        }
        equipmentMapper.updateEquipmentStateByEqual(orderSet);
    }

    // 半小时更新一次设备记录
    public void fillInEquipmentRecordMethod() {
    	try {
    		Map map = new HashMap();
    		// 更新设备记录
    		equipmentMapper.insertEquipmentRecordBySchedule(map);
    	}catch(Exception e) {
    		
    	}
    	try {
    		Map map = new HashMap();
    		// 更新设备记录
    		materService.timeingSendRequest();
    	}catch(Exception e) {
    		
    	}
//        energyMapper.updateAction(map);
    }

    // //采集电气 每天晚上十一点半采集一次啊
    // public void updateActionMethod() {
    // Map map=new HashMap();
    // //采集电气
    // energyMapper.updateAction(map);
    // }

    /**
     * title 消息头 userId 接收消息人 typeMessage 消息类型 dateString 时间字符串 bodyMessage 消息体
     * pageType 跳转页面 定时发送信息(拖期的采购单) 李斌
     */
    public void sendMessageUtil(String title, String userId, String typeMessage, String dateString, String bodyMessage,
                                String pageType) {
        com.alibaba.fastjson.JSONObject data = WeixinTemplateList.packJsonToWarningNotice(title, typeMessage,
                dateString, bodyMessage, null, null, null, null);
        // 查询openId
        List<String> openIds = weiXinPeopleMapper.getOpenIdByUserId(userId);
        if (openIds == null || openIds.size() < 1) {
            return;
        }
        // 获取accessToken
        String accessToken = weiXinService.getAccessToken(null);
        // 发送消息
        WeixinTemplateSender.sendWechatmsgToUser(openIds.get(0), WeiXinParamesUtil.exceptionTemplateID,
                WeiXinParamesUtil.messageLink + "?loginToken=" + openIds.get(0) + "&pageType=" + pageType, data,
                accessToken);
    }

    /**
     * 发送采购拖期信息 @date 2018年6月5日 上午10:49:12 @author 李斌 @return void @throws
     */
    public void sendPurchaseMessage(Map<String, Object> map, String bodyMessage) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = simpleDateFormat.format(new Date());
        // 制单人
        Set<String> createUsers = new HashSet<String>();
        // 采购人
        Set<String> purchasePeoples = new HashSet<String>();
        // 获取订单采购单
        List<PurchaseOrderDetailPojo> purchaseOrderDetailPojos = null;
        purchaseOrderDetailPojos = purchaseOrderMapper.getPurchaseOrderByPageData(map);
        if (purchaseOrderDetailPojos == null) {
            return;
        }
        //过滤公司设定中,某时间段内的采购单
        CompanyBean companyBean = userMapper.getCompanyInfo(map.get("loginCompany").toString());
        Iterator<PurchaseOrderDetailPojo> iterator = purchaseOrderDetailPojos.iterator();
        String format = "yyyy-MM-dd";
        while(iterator.hasNext()) {
        	PurchaseOrderDetailPojo purchasePojo = iterator.next();
	        if(companyBean.getNotShowTardinessStartDate() == null && companyBean.getNotShowTardinessEndDate() == null) {
	        }else if(companyBean.getNotShowTardinessStartDate() != null && companyBean.getNotShowTardinessEndDate() != null) {
	        	long startTime = TimeAndUnix.time2number(companyBean.getNotShowTardinessStartDate(),format);
	        	long endTime = TimeAndUnix.time2number(companyBean.getNotShowTardinessEndDate(),format);
	        	long createTime = TimeAndUnix.time2number(purchasePojo.getCreateTime(),format);
	        	if(createTime>=startTime && createTime<=endTime) {
	        		iterator.remove();
	        	}
	        }else if(companyBean.getNotShowTardinessStartDate() != null) {
	        	long startTime = TimeAndUnix.time2number(companyBean.getNotShowTardinessStartDate(),format);
	        	long createTime = TimeAndUnix.time2number(purchasePojo.getCreateTime(),format);
	        	if(createTime>=startTime) {
	        		iterator.remove();
	        	}
	        }else if(companyBean.getNotShowTardinessEndDate() != null){
	        	long endTime = TimeAndUnix.time2number(companyBean.getNotShowTardinessEndDate(),format);
	        	long createTime = TimeAndUnix.time2number(purchasePojo.getCreateTime(),format);
	        	if(createTime<=endTime) {
	        		iterator.remove();
	        	}
	        }
        }
        if (purchaseOrderDetailPojos.size()<1) {
            return;
        }
        // 获取异常消息推送人
        List<String> userIdList = weChatToMessageService
                .getWeChatNewsUserIdListByParam(map.get("loginCompany").toString(), null, null, "1");
        for (PurchaseOrderDetailPojo pojo : purchaseOrderDetailPojos) {
            // 添加制单人
            createUsers.add(pojo.getCreateUser());
            // 添加采购人
            purchasePeoples.add(pojo.getPurchasePeople());
        }
        map.put("userNames", createUsers);
        List<UserBean> createUserBeans = userMapper.getUserBeanByNames(map);
        map.put("userNames", purchasePeoples);
        List<UserBean> purchasePeopleBeans = userMapper.getUserBeanByNames(map);
        // 创建人与采购人的集合
        List<String> createUserAndPurchasePeople = new ArrayList<String>();
        String purchaseType = "";
        if (map.get("type").toString().equals("1")) {// 订单采购单
            purchaseType = "订单采购单";
        } else {
            purchaseType = "库存采购单";
        }
        for (UserBean createUser : createUserBeans) {
            int i = 0;
            for (PurchaseOrderDetailPojo pojo : purchaseOrderDetailPojos) {
                if (pojo.getType().equals(1) && createUser.getUserName().equals(pojo.getCreateUser())) {// 订单采购
                    i++;
                } else if (pojo.getType().equals(2) && createUser.getUserName().equals(pojo.getCreateUser())) {// 库存采购
                    i++;
                }
            }
            String redirectUrl = "";
            if (i > 0) {
                redirectUrl = RedirectUrlUtil.queryPurchaseOrder + "#type=" + map.get("type").toString()
                        + "&createUser=" + createUser.getId() + "&tardinessMin="
                        + ((Integer) map.get("tardinessMin") == null ? ""
                        : (Integer) map.get("tardinessMin")) + "&tardinessMax="
                        + (Integer) map.get("tardinessMax") + "&status=1";
                this.sendMessageUtil("采购单拖期异常信息", createUser.getId(), purchaseType + "拖期", dateString, bodyMessage + i,
                        redirectUrl);
            }
            createUserAndPurchasePeople.add(createUser.getId());
        }
        for (UserBean purchasePeople : purchasePeopleBeans) {
            int i = 0;
            for (PurchaseOrderDetailPojo pojo : purchaseOrderDetailPojos) {
                if (pojo.getType().equals(1) && purchasePeople.getUserName().equals(pojo.getPurchasePeople())) {// 订单采购
                    i++;
                } else if (pojo.getType().equals(2) && purchasePeople.getUserName().equals(pojo.getPurchasePeople())) {// 库存采购
                    i++;
                }
            }
            if (i > 0) {
                String redirectUrl = RedirectUrlUtil.queryPurchaseOrder + "#type=" + (Integer) map.get("type")
                        + "&purchasePeople=" + purchasePeople.getId() + "&tardinessMin="
                        + ((Integer) map.get("tardinessMin") == null ? ""
                        : (Integer) map.get("tardinessMin")) + "&tardinessMax="
                        + (Integer) map.get("tardinessMax") + "&status=1";

                this.sendMessageUtil("采购单拖期异常信息", purchasePeople.getId(), purchaseType + "拖期", dateString,
                        bodyMessage + i, redirectUrl);
            }
            createUserAndPurchasePeople.add(purchasePeople.getId());
        }
        // 取userIdList不在createUserAndPurchasePeople中的用户
        List<String> userList = ArrayUtils.removeAll(userIdList, createUserAndPurchasePeople);
        for (String userId : userList) {
            if (purchaseOrderDetailPojos.size() > 0) {
                String redirectUrl = RedirectUrlUtil.queryPurchaseOrder + "#type=" + (Integer) map.get("type")
                        + "&tardinessMin=" + ((Integer) map.get("tardinessMin") == null ? ""
                        : (Integer) map.get("tardinessMin")) + "&tardinessMax="
                        + (Integer) map.get("tardinessMax") + "&status=1";
                this.sendMessageUtil("采购单拖期异常信息", userId, purchaseType + "拖期", dateString,
                        bodyMessage + purchaseOrderDetailPojos.size(), redirectUrl);
            }
        }
    }

    /**
     * 发送拖期信息 @date 2018年7月26日 下午3:58:00 @author 李斌 @return void @throws
     */
    public void sendMessageByTardiness() {
        // 采购拖期
        try {
            // 获取采购单中的所有公司名称
            List<String> companyList = orderMapper.getCompanyNameByPurchase();
            Map<String, Object> map = new HashMap<String, Object>();
            for (String company : companyList) {
                /**
                 * 接近拖期的
                 */
                map.put("loginCompany", company);
                map.put("status", 1);
                map.put("type", 1);
                map.put("tardinessMin", 1);
                map.put("tardinessMax", 5);
                String notTardiness = "五天内即将拖期的订单数:";
                // 发送订单采购拖期信息
                this.sendPurchaseMessage(map, notTardiness);
                map.put("type", 2);
                // 发送库存采购信息
                this.sendPurchaseMessage(map, notTardiness);
                /**
                 * 已经拖期的
                 */
                map.put("tardinessMin", null);
                map.put("tardinessMax", -1);
                String isTardiness = "已拖期的订单数:";
                map.put("type", 1);
                // 发送订单采购拖期信息
                this.sendPurchaseMessage(map, isTardiness);
                map.put("type", 2);
                // 发送库存采购信息
                this.sendPurchaseMessage(map, isTardiness);
            }
        } catch (Exception e) {

        }

        // 生产拖期
        try {
            this.getTimerDelaySendMessage();
        } catch (Exception e) {

        }
        // 产能
        try {
            this.getCapacitySendMessage();
        } catch (Exception e) {

        }
        // 尾数
        try {
            this.getMantissaSendMessage();
        } catch (Exception e) {

        }

        // 周转量
        try {
            this.getTurnoverSendMessage();
        } catch (Exception e) {

        }
        // 订单拖期提醒
        try {
            this.getOrderDutySendMessage();
        } catch (Exception e) {

        }
        // 库存下限警报
        try {
            this.sendMssageBySafetyStockMin();
        } catch (Exception e) {
            // TODO: handle exception
        }
        // 入库结算通知警报
        try {
            this.sendWarehouseAccount();
        } catch (Exception e) {
            // TODO: handle exception
        }
        // 公司报工情况提醒
        try {
            this.sendReportCompany();
        } catch (Exception e) {
            // TODO: handle exception
        }
        // 公司报工情况提醒
        try {
        	this.setCompanyUseDetailToRedis();
        } catch (Exception e) {
        	// TODO: handle exception
        }

    }

    /**
     * 发送库存下限报警信息 @date 2018年7月26日 下午3:59:24 @author 李斌 @return void @throws
     */
    public void sendMssageBySafetyStockMin() {
        // 获取所有应发送警报的物料信息
        List<CompanyMaterialTableBean> companyMaterialList = basicDataMapper.getCompanyNameByMaterial();
        // 公司集合
        Set<String> companySet = new HashSet<String>();
        for (CompanyMaterialTableBean companyMaterialTableBean : companyMaterialList) {
            companySet.add(companyMaterialTableBean.getCompany());
        }
        Iterator<String> iterator = companySet.iterator();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        String title = "库存下限报警";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
        String dateString = sdf.format(new Date());
        while (iterator.hasNext()) {
            String company = iterator.next();
            paramMap.put("loginCompany", company);
            for (CompanyMaterialTableBean companyMaterialTableBean : companyMaterialList) {
                // 匹配公司名
                if (companyMaterialTableBean.getCompany().equals(company)) {
                    String bodyMessage = "物料名称-" + companyMaterialTableBean.getMaterialName() + " 物料规格-"
                            + (companyMaterialTableBean.getModel() == null ? "" : companyMaterialTableBean.getModel())
                            + " 色号-"
                            + (companyMaterialTableBean.getColor() == null ? "" : companyMaterialTableBean.getColor())
                            + " 供应商-" + companyMaterialTableBean.getProviderName() + " ---目前库存数:"
                            + companyMaterialTableBean.getCount();
                    companyMaterialService.sendSafetyStockMinMessage(title, bodyMessage, dateString, paramMap,
                            RedirectUrlUtil.queryStock, "8", 0);
                }
            }
        }
    }

    /**
     * 发送入库结算通知信息 @date 2018年8月8日 下午4:05:47 @author 李斌 @return void @throws
     */
    public void sendWarehouseAccount() {
        List<WarehouseInOutDetailBean> warehouseInOutDetailBeans = orderMapper.getWarehouseInDetailByScheduleJob();
        // 公司set
        Set<String> companySet = new HashSet<String>();
        for (WarehouseInOutDetailBean warehouseInOutDetailBean : warehouseInOutDetailBeans) {
            companySet.add(warehouseInOutDetailBean.getCompany());
        }
        Iterator<String> iterator = companySet.iterator();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        String title = "入库结算日期临近报警,一周内需结算";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
        String dateString = sdf.format(new Date());
        // 订单采购单入库
        List<WarehouseInOutDetailBean> groupTypeListOne = new ArrayList<WarehouseInOutDetailBean>();
        // 库存采购单入库
        List<WarehouseInOutDetailBean> groupTypeListTwo = new ArrayList<WarehouseInOutDetailBean>();
        while (iterator.hasNext()) {
            String company = iterator.next();
            paramMap.put("loginCompany", company);
            String bodyMessage = "一周内需结算的入库单数量为:";
            for (WarehouseInOutDetailBean warehouseInOutDetailBean : warehouseInOutDetailBeans) {
                // 匹配公司名
                if (warehouseInOutDetailBean.getCompany().equals(company)) {
                    if (warehouseInOutDetailBean.getType() == 1) {
                        groupTypeListOne.add(warehouseInOutDetailBean);
                    } else if (warehouseInOutDetailBean.getType() == 3) {
                        groupTypeListTwo.add(warehouseInOutDetailBean);
                    }
                }
            }
            if (groupTypeListOne.size() > 0) {
                companyMaterialService.sendSafetyStockMinMessage(title, bodyMessage + groupTypeListOne.size(),
                        dateString, paramMap, RedirectUrlUtil.warehouseInSumMoney, "9", 1);
            }
            if (groupTypeListTwo.size() > 0) {
                companyMaterialService.sendSafetyStockMinMessage(title, bodyMessage + groupTypeListTwo.size(),
                        dateString, paramMap, RedirectUrlUtil.warehouseInSumMoney, "9", 2);
            }
            groupTypeListOne.clear();
            groupTypeListTwo.clear();
        }
    }

    /**
     * 每天6-22点 每1分钟执行一次，发送考勤提示信息 
     * @author 王荣
     */
    public void sendAttendTipsMessage() {
        System.out.println("-------------发送考勤提醒定时器启动------------");
        // 获取时间范围内的排班记录，为空表示没到提示时间
        List<AttendPlanBean> attendPlanList = dingTalkMapper.getAttendPlan();
        if (attendPlanList != null && attendPlanList.size() > 0) {
            String accessToken = weiXinService.getAccessToken(null);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = sdf.format(new Date());
            for (AttendPlanBean attendPlanBean : attendPlanList) {
                String openId = attendPlanBean.getOpenId();
                String userName = attendPlanBean.getUserName();
                if (openId != null && !"".equals(openId)) {
                    String tips = "";
                    switch (attendPlanBean.getCheckType()) {
                        case "1":
                            tips = "还有" + attendPlanBean.getDateDiffMinutes() + "分钟就要上班啦，别忘记打卡哦~今天继续向着梦想出发吧";
                            break;
                        case "0":
                            tips = "已到打卡时间，别忘记打卡哦~放下工作的压力，用笑容面对家人";
                            break;
                    }
                    /** 考勤通知模板 */
                    com.alibaba.fastjson.JSONObject data =
                            WeixinTemplateList.packJsonToCheckWork("考勤打卡", userName, "", time, tips
                                    , null, null, null, null, null);
                    /** 发送微信消息 */
                    String message = WeixinTemplateSender.sendWechatmsgToUser(openId,
                            "X7ZQo8XNaQf_qS63eV1R6oqXeo1GSXBXSU6w0pS9esI", null, data, accessToken);
                    if ("success".equals(message)) {
                        message = userName + "消息发送成功";
                    } else {
                        message = userName + "消息发送异常：" + message;
                    }
                    System.out.println(message);
                }
            }
        }
    }
    
    /**
     * 每天凌晨01:00执行，生成每日工资记录，计算昨天的工资并保存记录
     * @author 王荣
     */
    public void generateDailyPayrollRecord() {
    	try {
			materService.timeingRegisterMater();//每天向第三方服务注册未注册完成的仪表
		} catch (Exception e) {
			
		}
    	
    	
    	
        //获取昨天
        String date = new DateTime().minusDays(1).toString("yyyy-MM-dd");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("startDate", date);
        map.put("endDate", date);
        try {
        	attendanceService.saveAttendDailySalaryDetail(attendanceService.calculateSalary(map));
		} catch (ParseException e) {
			e.printStackTrace();
		}
    }
    
    /**
     * 每日凌晨02:00执行， 定时执行修改工资任务 修改今天的工资
     * @author 王荣
     */
    public void updateSalaryTimerTask() {
    	
    	try {
    		attendanceService.updateSalaryTimerTask();
    	}catch(Exception e ) {
    		
    	}
    	try {
    		this.setYesterdayEnergy();
    	}catch(Exception e) {
    	}
    }

    /**
     * 每月1号00:30执行 定时保存上月的员工工资明细设定记录
     * @author 王荣
     */
    public void saveFinanceDetailByMonth() {
    	attendanceService.saveFinanceDetailByMonth();
    }
    
    /**
     * 每天下午14:00点执行，发送未处理考勤审批信息 
     * 例：今天还有几个审批单待您处理
     * @author 王荣
     */
    public void sendPendingApprovalMessage() {
    	List<PendingApprovalInfoPojo> pendingApprovalInfoPojoList = attendanceService.getPendingApprovalMessage();
    	/* 如果没有 直接返回 */
    	if(pendingApprovalInfoPojoList==null || pendingApprovalInfoPojoList.size()<=0) return;
    	/* 循环外获取accessToken */
    	String accessToken = weiXinService.getAccessToken(null); 
    	for (PendingApprovalInfoPojo pendingApprovalInfoPojo : pendingApprovalInfoPojoList) {
    		/* 审核人openId */
    		String openId = pendingApprovalInfoPojo.getOpenId();
    		String approvalType = pendingApprovalInfoPojo.getApprovalList().get(0).getApprovalType()+"";
    		String url = "";
    		if("1,2,3".indexOf(approvalType)>-1) {//请假 加班 补卡
    			url = WeiXinParamesUtil.messageLink+"?loginToken="+openId+"&pageType="+"/phoneApp/approvalMgr#type=1";
    		}
    		if("4,5,6".indexOf(approvalType)>-1) {//报销 处罚 奖励
    			url = WeiXinParamesUtil.messageLink+"?loginToken="+openId+"&pageType="+"/phoneApp/financeApprovalMgr#type=1";
    		}
    		/* 发送微信消息 */
			WeixinTemplateSender.sendWechatmsgToUser(openId, 
					WeiXinParamesUtil.watiApprovalTemplateID, 
					url, 
					WeixinTemplateList.packJsonWatiApproval("今天还有"+pendingApprovalInfoPojo.getApprovalList().size()+"个审批单待您处理", "", "", "", "","","点击进入审批页面",
							null, null, null, null, null,null,null), 
					accessToken);
		}
    }

    /**
     * 生产拖期异常
     */
    public void getTimerDelaySendMessage() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String dateString = sdf.format(new Date());
        List<ProductionExceptionBean> xx = workshopMapper.getTimerDelaySendMessage();
        List<ProductionExceptionBean> yy = workshopMapper.getSoonDelaySendMessage();
        for (ProductionExceptionBean pp : yy) {
            List<String> userIdList = weChatToMessageService.getWeChatNewsUserIdListByParam(pp.getCompany(),
                    pp.getDeptId(), pp.getWorkShopId(), "2");
            if (userIdList != null && userIdList.size() > 0) {
                List<WeiXinPeopleBean> weiXinPeopleList = weiXinPeopleMapper.getWeiXinPeopleByUserIdList(userIdList);
                if (weiXinPeopleList != null && weiXinPeopleList.size() > 0) {
                    List<DutyBean> listDuty = pp.getListDuty();
                    String soonDelay = "";
                    if (listDuty == null || listDuty.size() <= 0) {
                        soonDelay = "恭喜您，本车间没有即将拖期的订单";
                    } else {
                        soonDelay = "三天内即将拖期的订单数：" + listDuty.size();
                    }
                    for (WeiXinPeopleBean weiXinPeopleBean : weiXinPeopleList) {
                        this.sendMessageUtilByOpenId(pp.getWorkShopName() + "车间即将拖期订单", weiXinPeopleBean, "三天内将拖期异常",
                                dateString, soonDelay, RedirectUrlUtil.workshopDelay);
                    }
                }
            }
        }

        for (ProductionExceptionBean pp : xx) {
            List<String> userIdList = weChatToMessageService.getWeChatNewsUserIdListByParam(pp.getCompany(),
                    pp.getDeptId(), pp.getWorkShopId(), "2");
            if (userIdList != null && userIdList.size() > 0) {
                List<WeiXinPeopleBean> weiXinPeopleList = weiXinPeopleMapper.getWeiXinPeopleByUserIdList(userIdList);
                if (weiXinPeopleList != null && weiXinPeopleList.size() > 0) {
                    List<DutyBean> listDuty = pp.getListDuty();
                    int three = 0;
                    int four = 0;
                    String soonDelay = "";
                    if (listDuty == null || listDuty.size() <= 0) {
                        soonDelay = "恭喜您，本车间没有拖期的订单";
                    } else {
                        for (DutyBean duty : listDuty) {
                            if (duty.getDelayDay() >= 3) {
                                four++;
                            } else {
                                three++;
                            }
                        }
                        soonDelay = "拖期三天内订单数：" + three + "   拖期三天以上订单数：" + four;
                    }
                    for (WeiXinPeopleBean weiXinPeopleBean : weiXinPeopleList) {
                        this.sendMessageUtilByOpenId(pp.getWorkShopName() + "车间拖期异常", weiXinPeopleBean, "生产异常",
                                dateString, soonDelay, RedirectUrlUtil.workshopDelay);
                    }
                }
            }
        }
    }

    /**
     * 日产能提醒
     *
     * @throws ParseException
     */
    public void getCapacitySendMessage() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String dateString = sdf.format(new Date());
        String day = TimeAndUnix.isToDayOrLastDay();
        List<ProductionExceptionBean> xx = workshopMapper.getCapacitySendMessage(day);
        for (ProductionExceptionBean pp : xx) {
            List<String> userIdList = weChatToMessageService.getWeChatNewsUserIdListByParam(pp.getCompany(),
                    pp.getDeptId(), pp.getWorkShopId(), "5");
            if (userIdList != null && userIdList.size() > 0) {
                List<WeiXinPeopleBean> weiXinPeopleList = weiXinPeopleMapper.getWeiXinPeopleByUserIdList(userIdList);
                for (WeiXinPeopleBean weiXinPeopleBean : weiXinPeopleList) {
                    this.sendMessageUtilByOpenId(pp.getWorkShopName() + "车间日产能提醒", weiXinPeopleBean, "产能提醒", dateString,
                            pp.getWorkShopName() + "车间" + day + "日产能为：" + pp.getQualifiedCount(),
                            RedirectUrlUtil.indexHtml);
                }
            }
        }
    }

    /**
     * 尾数提醒
     *
     * @throws ParseException
     */
    public void getMantissaSendMessage() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String dateString = sdf.format(new Date());
        List<ProductionExceptionBean> xx = workshopMapper.getMantissaSendMessage();
        for (ProductionExceptionBean pp : xx) {
            List<String> userIdList = weChatToMessageService.getWeChatNewsUserIdListByParam(pp.getCompany(),
                    pp.getDeptId(), pp.getWorkShopId(), "3");
            if (userIdList != null && userIdList.size() > 0) {
                List<WeiXinPeopleBean> weiXinPeopleList = weiXinPeopleMapper.getWeiXinPeopleByUserIdList(userIdList);
                if (weiXinPeopleList != null && weiXinPeopleList.size() > 0) {
                    List<DutyBean> listDuty = pp.getListDuty();
                    String message = "";
                    if (listDuty == null || listDuty.size() <= 0) {
                        message = "恭喜您，本车间没有尾数异常";
                    } else {
                        message = "当前车间尾数异常条数为：" + listDuty.size();
                    }
                    for (WeiXinPeopleBean weiXinPeopleBean : weiXinPeopleList) {
                        this.sendMessageUtilByOpenId(pp.getWorkShopName() + "车间尾数异常", weiXinPeopleBean, "生产异常",
                                dateString, message, RedirectUrlUtil.workshopMantissa);
                    }
                }
            }
        }
    }

    /**
     * 周转量提醒
     *
     * @throws ParseException
     */
    public void getTurnoverSendMessage() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String dateString = sdf.format(new Date());
        List<ProductionExceptionBean> xx = workshopMapper.getTurnoverSendMessage();
        for (ProductionExceptionBean pp : xx) {
            List<String> userIdList = weChatToMessageService.getWeChatNewsUserIdListByParam(pp.getCompany(),
                    pp.getDeptId(), pp.getWorkShopId(), "4");
            if (userIdList != null && userIdList.size() > 0) {
                List<WeiXinPeopleBean> weiXinPeopleList = weiXinPeopleMapper.getWeiXinPeopleByUserIdList(userIdList);
                if (weiXinPeopleList != null && weiXinPeopleList.size() > 0) {
                    String message = pp.getWorkShopName() + "周转量:" + pp.getTurnover() + " ("
                            + pp.getWorkShopStartTurnover() + " ~ " + pp.getWorkShopEndTurnover() + ")";
                    if (pp.getTurnover() < pp.getWorkShopStartTurnover()) {
                        message = message + "  周转量过小";
                    } else if (pp.getTurnover() > pp.getWorkShopEndTurnover()) {
                        message = message + "  周转量过大";
                    } else {
                        message = message + "  周转量正常";
                    }
                    for (WeiXinPeopleBean weiXinPeopleBean : weiXinPeopleList) {
                        this.sendMessageUtilByOpenId(pp.getWorkShopName() + "车间周转量", weiXinPeopleBean, "周转量提醒",
                                dateString, message, RedirectUrlUtil.turnover);
                    }
                }
            }
        }
    }

    /**
     * @param title
     * @param weiXinPeople
     * @param typeMessage
     * @param dateString
     * @param bodyMessage
     * @param pageType
     */
    public void sendMessageUtilByOpenId(String title, WeiXinPeopleBean weiXinPeople, String typeMessage,
                                        String dateString, String bodyMessage, String pageType) {
        com.alibaba.fastjson.JSONObject data = WeixinTemplateList.packJsonToWarningNotice(title, typeMessage,
                dateString, bodyMessage, null, null, null, null);
        // 获取accessToken
        String accessToken = weiXinService.getAccessToken(null);
        // 发送消息
        WeixinTemplateSender.sendWechatmsgToUser(weiXinPeople.getOpenid(),
                WeiXinParamesUtil.exceptionTemplateID,
                WeiXinParamesUtil.messageLink + "?loginToken=" + weiXinPeople.getOpenid() + "&pageType=" + pageType,
                data, accessToken);
    }

    public void getOrderDutySendMessage() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String dateString = sdf.format(new Date());
        List<ProductionExceptionBean> xx = orderMapper.getOrderTimerDelaySendMessage(null, 1);
        List<ProductionExceptionBean> yy = orderMapper.getOrderTimerDelaySendMessage(null, 2);
        for (ProductionExceptionBean pp : yy) {
            List<String> userIdList = weChatToMessageService.getWeChatNewsUserIdListByParam(pp.getCompany(), null, null,
                    "7");
            if (userIdList != null && userIdList.size() > 0) {
                List<WeiXinPeopleBean> weiXinPeopleList = weiXinPeopleMapper.getWeiXinPeopleByUserIdList(userIdList);
                if (weiXinPeopleList != null && weiXinPeopleList.size() > 0) {
                    List<DutyBean> listDuty = pp.getListDuty();
                    String soonDelay = "";
                    if (listDuty == null || listDuty.size() <= 0) {
                        soonDelay = "恭喜您，没有即将拖期的订单";
                    } else {
                        soonDelay = "十天内即将拖期的订单数：" + listDuty.size();
                    }
                    for (WeiXinPeopleBean weiXinPeopleBean : weiXinPeopleList) {
                        this.sendMessageUtilByOpenId("公司订单即将拖期提醒", weiXinPeopleBean, "十天内将拖期异常", dateString, soonDelay,
                                RedirectUrlUtil.queryOrder + "#dutyStatus=2&startDate=2017-01-01");
                    }
                }
            }
        }

        for (ProductionExceptionBean pp : xx) {
            List<String> userIdList = weChatToMessageService.getWeChatNewsUserIdListByParam(pp.getCompany(), null, null,
                    "7");
            if (userIdList != null && userIdList.size() > 0) {
                List<WeiXinPeopleBean> weiXinPeopleList = weiXinPeopleMapper.getWeiXinPeopleByUserIdList(userIdList);
                if (weiXinPeopleList != null && weiXinPeopleList.size() > 0) {
                    List<DutyBean> listDuty = pp.getListDuty();
                    int four = 0;
                    String soonDelay = "";
                    if (listDuty == null || listDuty.size() <= 0) {
                        soonDelay = "恭喜您，没有拖期的订单";
                    } else {
                        for (DutyBean duty : listDuty) {
                            four++;
                        }
                        soonDelay = "拖期单数：" + four;
                    }
                    for (WeiXinPeopleBean weiXinPeopleBean : weiXinPeopleList) {
                        this.sendMessageUtilByOpenId("公司订单拖期提醒", weiXinPeopleBean, "订单拖期异常", dateString, soonDelay,
                                RedirectUrlUtil.queryOrder + "#dutyStatus=1&startDate=2017-01-01");
                    }
                }
            }
        }
    }

    /**
     * 发送当天报工情况记录
     */
    public void sendReportCompany() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = sdf.format(new Date());
        List<String> companyList = workshopMapper.getReportCompany(dateString);
        StringBuilder sb = new StringBuilder(dateString).append("报工公司");
        for (String xx : companyList) {
            sb.append("   ").append(xx);
        }
        // yechaobo
        WeiXinPeopleBean weiXinPeopleBean = new WeiXinPeopleBean();
        weiXinPeopleBean.setOpenid("o_THqw0u6q62kfSSW4YuBUOCUByc");
        this.sendMessageUtilByOpenId("报工公司提醒", weiXinPeopleBean, "报工公司提醒", dateString, sb.toString(),
                RedirectUrlUtil.reportCompany);
        // nate
        weiXinPeopleBean.setOpenid("o_THqw0_UhnWghEzp4DCHVZb23f8");
        this.sendMessageUtilByOpenId("报工公司提醒", weiXinPeopleBean, "报工公司提醒", dateString, sb.toString(),
                RedirectUrlUtil.reportCompany);

        companyList = workshopMapper.getCreateOrderCompany(dateString);
        sb = new StringBuilder(dateString).append("制单公司");
        for (String xx : companyList) {
            sb.append("   ").append(xx);
        }
        // yechaobo
        weiXinPeopleBean.setOpenid("o_THqw0u6q62kfSSW4YuBUOCUByc");
        this.sendMessageUtilByOpenId("制单公司提醒", weiXinPeopleBean, "制单公司提醒", dateString, sb.toString(),
                RedirectUrlUtil.createOrderCompany);
        // nate
        weiXinPeopleBean.setOpenid("o_THqw0_UhnWghEzp4DCHVZb23f8");
        this.sendMessageUtilByOpenId("制单公司提醒", weiXinPeopleBean, "制单公司提醒", dateString, sb.toString(),
                RedirectUrlUtil.createOrderCompany);
    }

    /**
     * 将公司使用情况存入redis
     */
    public List<Map> setCompanyUseDetailToRedis() {
    	List<Map> list=userMapper.getCompanyUseDetail();
    	RedisCache.setDataToRedis(RedisKey.COMPANY_USE_DETAIL, list, null);
    	return list;
    }


    /**
     * @Author: 李宇航
     * @Description: 每天7：30定时发送设备相关信息给相关公司的所有人
     * @Param: 无
     * @return: 无
     * @Date: 2018/10/30
     */
    public void sendEquipmentDetailOfYesterday() {
        String accessToken = weiXinService.getAccessToken(null);
        Map<String, Map<String, Map<String, List<String>>>> companyWeChatUsers = weChatToMessageService.
                getCompanyWeChatUsersByType(WeChatMessageType.EQUIPMENT_DETAIL);
        Map<String, Map<String, Map<String, List<EquipmentDetail>>>> groupEquipmentDetails = equipmentService.
                getGroupEquipmentDetails();
        for (String company : companyWeChatUsers.keySet()) {
            for (String deptId : companyWeChatUsers.get(company).keySet()) {
                if ("ALL".equalsIgnoreCase(deptId)) {
                    List<EquipmentDetail> dataList = new ArrayList<>();
                    List<String> openIdList = companyWeChatUsers.get(company).get("ALL").get("ALL");
                    if (groupEquipmentDetails.get(company) == null) continue;
                    groupEquipmentDetails.get(company).values()
                            .forEach(deptIdMap -> deptIdMap.values()
                                    .forEach(equipmentDetails -> equipmentDetails
                                            .forEach(dataList::add)));
                    sendMessageByDataAndOpenId(dataList, openIdList, accessToken,
                            TemplateClickUrl.EQUIPMENTDETAIL, deptId, "ALL");
                    continue;
                }
                for (String workShopId : companyWeChatUsers.get(company).get(deptId).keySet()) {
                    if ("ALL".equalsIgnoreCase(workShopId)) {
                        List<EquipmentDetail> dataList = new ArrayList<>();
                        List<String> openIdList = companyWeChatUsers.get(company).get(deptId).get("ALL");
                        if (groupEquipmentDetails.get(company) == null) {
                            continue;
                        }
                        if (groupEquipmentDetails.get(company).get(deptId) == null) {
                            continue;
                        }
                        groupEquipmentDetails.get(company).get(deptId).values()
                                .forEach(workshop -> workshop.forEach(dataList::add));
                        sendMessageByDataAndOpenId(dataList, openIdList, accessToken,
                                TemplateClickUrl.EQUIPMENTDETAIL, deptId, workShopId);
                        continue;

                    }
                    if (groupEquipmentDetails.get(company) == null) {
                        continue;
                    }
                    if (groupEquipmentDetails.get(company).get(deptId) == null) {
                        continue;
                    }
                    if (groupEquipmentDetails.get(company).get(deptId).get(workShopId) == null) {
                        continue;
                    }
                    List<EquipmentDetail> dataList = groupEquipmentDetails.get(company).get(deptId).get(workShopId);
                    List<String> openIdList = companyWeChatUsers.get(company).get(deptId).get(workShopId);
                    sendMessageByDataAndOpenId(dataList, openIdList, accessToken,
                            TemplateClickUrl.EQUIPMENTDETAIL, deptId, workShopId);
                }
            }
        }
    }

    private void sendMessageByDataAndOpenId(List<EquipmentDetail> dataList, List<String> openIdList,
                                            String accessToken, String url, String dept, String workshop) {
        StringBuilder sb = new StringBuilder();
        IntStream.range(0, dataList.size()).forEach(i -> {
            if (i == 0) {
                sb.append(dataList.get(i).packageAsWeChatMessage());
            } else {
                sb.append("设备：").append(dataList.get(i).packageAsWeChatMessage());
            }
        });
        sb.deleteCharAt(sb.length() - 1);
        JSONObject data = WeixinTemplateList.packageMessageWithColor(Color.BLANK,
                "设备信息",
                new DateTime().toString(TimeConst.SECOND_FORMAT_WITH_SEPARATOR),
                sb.toString(),
                "谢谢使用");
        openIdList.forEach(openId -> WeixinTemplateSender.sendWechatmsgToUser(openId,
                TemplateID.EQUIPMENTDETAIL,
                packageMessageUrl(url, dept, workshop, openId),
                data, accessToken));


    }

    private String packageMessageUrl(String url, String dept, String workshop, String openId) {
        return WeiXinParamesUtil.messageLink + "?loginToken=" + openId + "&pageType=" + url + "#dept=" + dept + "&workshop=" + workshop;
    }

    /**
     * @author 李宇航
     * @Description: 该定时器将每天记录宿舍用户用电记录  禁用了和请假了的用户不算
     * 每天晚上十一点五十九
     * @Date: 8:12 2018/12/11
     */
    public void insertDormUserUseRecords() {
        List<DormUserUseRecord> resultRecord = new ArrayList<>();
        //获取所有宿舍水电表记录
        List<DormUserUseRecord> allDormEnergyDegree = dormUserUseRecordMapper.listDormEnergyDegree();
        //获取水表电表最最后一次使用度数
        List<DormUserUseRecord> lastRecordOfAllDormEnergyDegree = dormUserUseRecordMapper.listLastRecordOfDormEnergyDegree();
        //获取没有请假的人员
        List<DormManageToUserBean> dormManageToUserBeans = dormUserUseRecordMapper.listDormNotLeavePerson();
        Map<String, DormUserUseRecord> lastRecordOfAllDormEnergyDegreeMap = new HashMap<>(20);//宿舍最后用电用水记录
        Map<String, Set<String>> dormToUserMap = new HashMap<>(20);//宿舍对应人员map
        //遍历一次水表电表最后一次保存记录
        for (DormUserUseRecord dormUserUseRecord : lastRecordOfAllDormEnergyDegree) {
            lastRecordOfAllDormEnergyDegreeMap.put(dormUserUseRecord.getDormId(), dormUserUseRecord);
        }
        /**
         * 设置宿舍人员
         */
        for (DormManageToUserBean dormManageToUserBean : dormManageToUserBeans) {
            Set<String> userIdSet = dormToUserMap.get(dormManageToUserBean.getDormId());
            if (userIdSet == null) {
            	userIdSet = new HashSet<String>();
            }
            userIdSet.add(dormManageToUserBean.getUserId());
            dormToUserMap.put(dormManageToUserBean.getDormId(),userIdSet);
        }
        
        /**
         * 遍历所有宿舍水电当前度数
         */
        for (DormUserUseRecord dormUserUseRecord : allDormEnergyDegree) {
            //宿舍最后一次水电度数
        	DormUserUseRecord lastRecordOfDormEnergyDegree = lastRecordOfAllDormEnergyDegreeMap.get(dormUserUseRecord.getDormId());
            if (lastRecordOfDormEnergyDegree == null) {
                dormUserUseRecord.setElectricalUsage(new BigDecimal(0));
                dormUserUseRecord.setWaterMeterUsage(new BigDecimal(0));
            } else {
                BigDecimal electricalDegree = lastRecordOfDormEnergyDegree.getElectricalDegree();
                BigDecimal waterMeterDegree = lastRecordOfDormEnergyDegree.getWaterMeterDegree();
                if (electricalDegree != null) {//目前度数减去之前度数
                    dormUserUseRecord.setElectricalUsage(dormUserUseRecord.getElectricalDegree().subtract(electricalDegree));
                } else {
                    dormUserUseRecord.setElectricalUsage(new BigDecimal(0));
                }
                if (waterMeterDegree != null) {
                    dormUserUseRecord.setWaterMeterUsage(dormUserUseRecord.getWaterMeterDegree().subtract(waterMeterDegree));
                } else {
                    dormUserUseRecord.setWaterMeterUsage(new BigDecimal(0));
                }
            }
            Set<String> userIdSet = dormToUserMap.get(dormUserUseRecord.getDormId());
            //宿舍有人
            if (userIdSet != null) {
                BigDecimal electricalUsedOfEveryone = new BigDecimal(0);
                BigDecimal waterUsedOfEveryone = new BigDecimal(0);
                if (dormUserUseRecord.getElectricalUsage() != null) {
                    electricalUsedOfEveryone = dormUserUseRecord.getElectricalUsage().divide(new BigDecimal(userIdSet.size()), 1, BigDecimal.ROUND_HALF_UP);
                }
                if (dormUserUseRecord.getWaterMeterUsage() != null) {
                    waterUsedOfEveryone = dormUserUseRecord.getWaterMeterUsage().divide(new BigDecimal(userIdSet.size()), 1, BigDecimal.ROUND_HALF_UP);
                }
                for (String userId : userIdSet) {
                    resultRecord.add(new DormUserUseRecord(dormUserUseRecord.getDormId(), Integer.valueOf(userId), electricalUsedOfEveryone, dormUserUseRecord.getElectricalDegree(), waterUsedOfEveryone, dormUserUseRecord.getWaterMeterDegree()));
                }

            } else {
                resultRecord.add(dormUserUseRecord);
            }
        }
        dormUserUseRecordMapper.saveAllRecodes(resultRecord);
    }

    public void baiduSimilarPic() {
        JedisPool jedisPool = RedisCache.getPool();
        Jedis jedis = jedisPool.getResource();
        try {
        	//删除图片操作
        	String deleteArray = jedis.lpop("similarPicDeleteForRemote");
        	if(deleteArray!=null&&deleteArray.length()>0) {
        		BaiduSimilarPicSearchUtils.similarPicDeleteForRemoteByContSign(deleteArray);
        	}
            //插入图片操作
    		String array = jedis.lpop("similarPicInsertForRemote");
    		if(array!=null&&array.length()>0) {
    			JSONArray arrayTwo = (JSONArray) JSONArray.parse(array);
        		Brief brief = JSON.parseObject(arrayTwo.get(0).toString(),Brief.class);
        		Tags tags = JSON.parseObject(arrayTwo.get(1).toString(),Tags.class);
        		String url = arrayTwo.get(2).toString();
        		org.json.JSONObject object = BaiduSimilarPicSearchUtils.similarPicInsertForRemote(brief, tags, url);
       			if(!object.has("error_code"))basicDataService.addSynImgsToBaiduCheckRedis(url, object);
    		}
		} finally {
			RedisCache.returnResource(jedisPool, jedis);
		}
        
    }
    /**
     * 查询打卡无效时间
     */
    public void  tblRealtimeGlog() {
    	System.out.println("###############定时器-查询打卡无效时间开始#################");
    	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    	Calendar calendar = Calendar.getInstance();
    	calendar.add(Calendar.DATE, -1);
    	
    	Map<String, Object> map = new HashMap<>();
    	map.put("clockStartTime", df.format(calendar.getTime()));//昨天
    	map.put("clockEndTime", df.format(new Date()));//今天
    	//查询昨天和当前数据
    	List<Map<String, Object>> list = dingTalkMapper.getInvalidClockTime(map);
    	System.out.println(list.size());
    	System.out.println(list.get(0));
    	//遍历循环数据然后和班次时间有效时间是否在范围内
    	//如果不是在范围内 当天时间遍历完毕则重新计算当天工资
    	for(int i=0;i<list.size();i++) {
    		//String guid=list.get(i).get("guid").toString();
    		int userId=Integer.valueOf(list.get(i).get("userId").toString());
    		//String baseCheckStartTime=list.get(i).get("base_check_start_time").toString();
    		//String baseCheckEndTime=list.get(i).get("base_check_end_time").toString();
    		String company=list.get(i).get("company").toString();
    		//将打卡无效时间移入另一张表 并移除
    		dingTalkMapper.removeClockRecordToInvalidClockTime(list.get(i));
    		//重新计算当前这个人员当时的工资
    		attendanceService.updateDailySalaryRecord(map.get("clockStartTime").toString(),map.get("clockEndTime").toString(),company,userId);
    		
    	}
    	System.out.println("###############定时器-查询打卡无效时间结束#################");
    }
    
    
    /**
     * 设置分期付款付款时间和已过期数
     * 每月28执行
     */
    public void setStagesTimeAndCount() {
    	//获取本月应付款记录
    	List<WarehouseInSumMoneyBean> warehouseInSumMoneyBeans =  companyMaterialService.getAllThisMonthStages();
    	
    	for(WarehouseInSumMoneyBean  oo:warehouseInSumMoneyBeans) {
    		//如果付款金额已经足够
    		if(oo.getInOutMoney()<=oo.getReceiptPaymentPrice()) {
    			continue;
    		}
    		//将上次付款时间设为本次付款时间
    		oo.setLastPayTime(oo.getPayTime());
    		//如果期数还有 设置时间为下个付款日期
    		if(oo.getStagesCount() > oo.getAleradyPayCount()) {
    			try {
					String time=TimeAndUnix.subMonth(oo.getPayTime(), oo.getStagesInterval());
					oo.setPayTime(time);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    				
				//设置上月应付金额
				BigDecimal inOutMoney = new BigDecimal(oo.getInOutMoney());
				BigDecimal receivePayMoney = new BigDecimal(oo.getReceiptPaymentPrice());
				BigDecimal stageCount= new BigDecimal(oo.getStagesCount());
				BigDecimal totalPayable = new BigDecimal(oo.getTotalPayable());
				BigDecimal surplusStagesCount = new BigDecimal(oo.getAleradyPayCount());
				surplusStagesCount=stageCount.subtract(surplusStagesCount);
				BigDecimal beforeSumMoney = new BigDecimal(oo.getBeforeSumMoney());
				oo.setTotalPayable((inOutMoney.subtract(beforeSumMoney)).divide(surplusStagesCount,4,BigDecimal.ROUND_HALF_DOWN).doubleValue());
				oo.setPayInThisMonth(receivePayMoney.subtract(beforeSumMoney).doubleValue());
				oo.setBeforeSumMoney(receivePayMoney.doubleValue());
    			oo.setAleradyPayCount(oo.getAleradyPayCount()+1);
    		}else {//没有下一期了应付金额就是剩下的所有
    			oo.setTotalPayable(oo.getInOutMoney() - oo.getReceiptPaymentPrice());
    		}
    	}
    	companyMaterialService.setInOutStageDateil(warehouseInSumMoneyBeans);
    }
    
    
    /**
     * 定时统计昨天仪表使用度数
     */
    public  void setYesterdayEnergy() {
    	try {
    		energyMapper.setYesterdayEnergy();  //定时统计昨天仪表的用量
    	}catch(Exception e) {
    		
    	}
    	
    	try {
    		setThisEquipmentCapacity();
    	}catch(Exception e) {
    		
    	}
    	
    }
    
    /**
     * 设置设备产能
     */
    public void setThisEquipmentCapacity() {
//    	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
//    	String month = simpleDateFormat.format(new Date());
//    	Map map=new HashMap();
//		map.put("month", month);
//		map.put("timeType", 2);
    	//定时设置当月设备产能，不包过当天
//    	try {
//    		List<DayCapacity> returnList = equipmentMapper.getEquipmentMonthCapacityDatail(map);
//    		RedisCache.setDataToRedis(RedisKey.EQUIPMENT_THIS_MONTH_NOT_DAY_CAPACITY, returnList, null);
//    	}catch(Exception e) {
//    		
//    	}
    	//定时设置当月设备产能，不包过当天
//    	try {
//    		List<ProductionExceptionBean> returnList = equipmentMapper.getMachineCapacity(map);
//    		RedisCache.setDataToRedis(RedisKey.EQUIPMENT_THIS_MONTH_NOT_DAY_CAPACITY_PROCESS, returnList, null);
//    	}catch(Exception e) {
//    		
//    	}
    	
    	/**
    	 * 保存昨日设备运行时间
    	 */
    	try {
    		equipmentService.setEquipmentStateTime();
    	}catch(Exception e) {
    		
    	}
    	List<EquipmentRecordPojo> list = equipmentMapper.getRecordData();
    	/**
    	 * 保存昨日设备产能
    	 */
    	try {
    		equipmentService.statisticsEquipmentCapacity(list);
    	}catch (Exception e) {
    		
		}
    	
    	/**
    	 * 保存设备报工信息
    	 */
    	try {
    		equipmentService.statisticsEquipmentProcessCapacity(list);
    	}catch(Exception e) {
    		
    	}
    	 try {
         	basicDataMapper.updateProcessReportMode(); 
         }catch(Exception e) {
         	
         }
    	
    	
    	//清楚设备日期
    	try {
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    		String toDay = sdf.format(new Date());//今天
    		Map<String, JSONObject> equipmentBoard = (Map<String, JSONObject>) RedisCache.getDataFromRedis("equipmentBoard");
    		for(String equipmentNo : equipmentBoard.keySet()) {
    			JSONObject jsonObject = equipmentBoard.get(equipmentNo);
    			String oldDay = jsonObject.getString("day");
    			if(!toDay.equals(oldDay)) {//如果日期不是今天
    				jsonObject.put("day", toDay);
    				jsonObject.put("count", 0);
    				equipmentBoard.put(equipmentNo, jsonObject);
        		}
    		}
    		RedisCache.setDataToRedis("equipmentBoard", equipmentBoard, null);
    	}catch(Exception e) {
    		
    	}
    	
    }

    /**
     * 每两小时执行一次定时器
     */
    public  void everyTwoHoursSchedulingMethod() {
    	//设置配套看板信息
    	orderService.orderMatchingDetailScheduleMethod();
    }
    
    /**
     *提醒公司服务到期
     */
    public void companyTimeOut() {
    	//获取公司今天在提醒时间到期时间范围内的公司及其负责人
    	Map map = new HashMap<>();
    	map.put("timeOut", "timeOut");
    	List<CompanyBean> list = companyMapper.getAllCompany(map);
    	for(CompanyBean bean : list) {
    		//发送消息
    		String accessToken = weiXinService.getAccessToken(null);
    		JSONObject jsonObject = WeixinTemplateList.sendCompanyTimeOut("您的系统数据服务即将到期", bean.getName(), bean.getEndTime(), "请尽快充值续期，以免影响你使用。", Color.RED.getColorCode(), null, null, null);
    		WeixinTemplateSender.sendWechatmsgToUser(bean.getOpenId(), "aS8oUWNLuL1iC-by9m51zrBbR6YQUoNl0AWNxJQYxBM", null, jsonObject, accessToken);
    	}
    }
}
